<template>
  <div class="event-list">
    <div class="common-list-view__v2">
      <div ref="tableDoContainer" class="operate-box">
        <div class="operate-box__left">
          <div ref="tableHeaderContainer" class="filter-wrapper bg-w">
            <form onsubmit="return false;">
                <div class="searh-input-box">
                <!-- 输入框搜索/重置 -->
                <div class="base-search-group input-with-append-search">
                    <el-input
                    v-model="searchParams.memberName"
                    :placeholder="$t('portal.dataBoard.loginTable.tip1')"
                    class="task-mr12 search-input"
                    >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    <el-button
                        type="primary"
                        slot="append"
                        @click="
                        searchParams.pageNum = 1;
                        search();
                        "
                        native-type="submit"
                        v-track="$track.formatParams('KEYWORD_SEARCH')"
                    >
                        {{$t('common.base.search')}}
                    </el-button>
                    </el-input>
                    <el-button type="ghost" class="reset-btn" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')"
                    >{{$t('common.base.reset')}}</el-button
                    >
                </div>
                <!-- 高级搜索 -->
                <div
                    class="advanced-search-btn pointer"
                    @click.self.stop="panelSearchAdvancedToggle"
                >
                    <i class="iconfont icon-filter"></i>
                    {{$t('common.base.advancedSearch')}}
                </div>
                </div>
            </form>
            </div>
        </div>
        <div class="operate-box__right">
          <!-- 更多操作 -->
          <el-dropdown v-if="isButtonDisplayed && exportIn">
            <div class="cur-point">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed && exportIn">
                <div @click="handleExport(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed && exportIn">
                <div @click="handleExport(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div
              :class="['task-pointer', 'cur-point', 'ml_12']"
              @click="showAdvancedSetting"
              v-track="$track.formatParams('SELECT_COLUMN')"
            >
              <span>{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        ref="table"
        class="mt_12 bbx-normal-list-box"
        stripe
        :row-key="getRowKey"
        :data="Page.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        v-loading="loading"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading"></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
          :reserve-selection="true"
        ></el-table-column>
        <template v-for="column in columns">
          <el-table-column
            v-if="column && column.show"
            show-overflow-tooltip
            :align="column.align"
            :key="column.field"
            :label="column.displayName"
            :min-width="column.minWidth"
            :prop="column.field"
            :sortable="column.sortable"
            :width="column.width"
            :resizable="true"
            :fixed="column.fixLeft || false"
          >
            <template slot-scope="scope">
              <template v-if="column.renderCell">
                <base-table-cell
                  :render-cell="column.renderCell"
                  :column="column"
                  :row="scope.row"
                ></base-table-cell>
              </template>
                <template v-else-if="column.field === 'phone'">
                  <template v-if="scope.row.phone">
                    <div>{{scope.row.phone}}</div>
                     <biz-call-icon :value="scope.row.phone" />
                  </template>
                </template>
                <!-- 用户标签 -->
                <template v-else-if="column.field === 'tag'">
                    <template v-if="scope.row.tag">
                        <div class="tag_div">
                            <el-tag v-for="tag in Object.values(scope.row.tag)" :key="`${tag}_${column.field}`">{{ tag }}</el-tag>
                        </div>
                    </template>
                </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          fixed="right"
          :label="$t('common.base.operation')"
          width="200">
          <template slot-scope="scope">
            <template v-if="!scope.row.knownCustomer">
                <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="
                    createCustomer(
                        scope.row.memberId,
                        scope.row.phone,
                        scope.row.email
                    )"
                >
                    {{$t('portal.dataBoard.loginTable.btn.btn1')}}
                </el-button>
                <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="saveLinkman(scope.row.phone,scope.row.email,scope.row.memberId)"
                >
                    {{$t('portal.dataBoard.loginTable.btn.btn2')}}
                </el-button>
            </template>
            <template v-else>
              <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="openCustomer(scope.row.customerId)"
              >
                  {{$t('common.base.detail')}}
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-12 pad-b-16 bg-w pad-t-16">
        <div class="list-info" >
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ Page.total || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
                <span  place="count"
                class="color-primary pad-l-5 pad-r-5"
              >{{ multipleSelection.length }}</span>
            </i18n>
            <span class="color-primary cur-point" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="Page.total"
        >
        </el-pagination>
      </div>

      <!-- 高级搜索框 -->
      <base-search-drawer
        :show.sync="visible"
        :storage-key="advancedColumnNumStorageKey"
        @reset="resetParams"
        @search="advancedSearch"
        @changeWidth="setAdvanceSearchColumn"
        @getColumnNum="setAdvanceSearchColumn"
      >
        <base-search-panel
          ref="searchPanel"
          :column-num="columnNum"
          :fields="advanceSearchColumn"
        />
      </base-search-drawer>

      <!-- 导出工单 -->
      <base-export-group
        ref="exportPanel"
        :alert="exportAlert"
        :columns="exportColumnList"
        :build-params="buildExportParams"
        :group="true"
        :validate="checkExportCount"
        method="post"
        :action="doorLoginListExport"
      />

      <!-- 选择列 -->
      <biz-select-column ref="advanced" mode="portal" @save="saveColumnStatus" />

      <!-- 添加到现有客户的对话框 -->
        <el-dialog
            :title="$t('im.detail.title2')"
            :visible.sync="saveDialogVisible"
            width="420px"
            @close="saveDialogClosed"
            >
            <!-- 内容主体区域 -->
            <el-form
                :model="saveForm"
                :rules="saveFormRules"
                ref="saveFormRef"
                
                label-position="top"
            >
                <el-form-item :label="$t('common.base.customer')" prop="customer">
                    <customer-select
                        style="line-height: initial;"
                        v-model="customer"
                        :field="customerField"
                        :remote-method="searchCustomer"
                        :update-customer="updateCustomer"
                        :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.customer')})"
                    ></customer-select>
                </el-form-item>

                <el-form-item :label="$t('im.detail.label1')" prop="type">
                    <el-radio v-model="saveForm.type" :label="0">{{$t('im.detail.label2')}}</el-radio>
                    <el-radio v-model="saveForm.type" :label="1">{{$t('im.detail.label3')}}</el-radio>
                </el-form-item>

                <template>
                <el-form-item v-if="saveForm.type==0" :label="$t('common.base.contact')" prop="name">
                    <el-input
                    v-model="saveForm.name"
                    :placeholder="$t('common.placeholder.inputSomething', {data1:$t('common.base.contact')})"
                    ></el-input>
                </el-form-item>

                <el-form-item v-if="saveForm.type==1" :label="$t('common.base.contact')" prop="linkman">
                    <biz-remote-select
                    ref="linkman"
                    :placeholder="$t('im.detail.pla2')"
                    :cleared="true"
                    v-model="saveForm.linkman"
                    :remote-method="searchLinkman"
                    >
                    </biz-remote-select>
                </el-form-item>
                </template>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="saveDialogVisible = false">{{$t('common.base.cancel')}}</el-button>
                <el-button type="primary" @click="saveUserClick"
                >{{$t('common.base.confirm')}}</el-button
                >
            </span>
        </el-dialog>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import * as _ from 'lodash';
import Page from '@model/Page';

import { loginRecordPage, getUserTag, unknownUserRelationLinkman } from '@src/api/PortalApi';
import * as TaskApi from '@src/api/TaskApi.ts';

import {
  getColumnFields,
  getAdvancedFields,
  getExportSystemInfo,
} from '@src/modules/portal/portalData/field.js';

/** components */
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import { formatDate } from '@src/util/lang';
import { storageGet, storageSet } from '@src/util/storage';

/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts';
/* export & import */
import { doorLoginListExport } from '@src/api/Export';

import AuthUtil from '@src/util/auth';
import { safeNewDate } from '@src/util/time';

import AuthMixin from '@src/mixins/authMixin';
import FormMixin from '@src/component/form/mixin/form'

import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { linkmanSelectConversion } from '@src/util/conversionFunctionUtil.ts'
import { defaultTableData } from '@src/util/table'

const DOOR_USER_LIST_KEY = 'door_user_list';
const DOOR_USER_PAGE_SIZE_KEY = 'door_user_page_size';
import i18n from '@src/locales'

export default {
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    'customer-select': {
            name: 'customer-select',
            mixins: [FormMixin],
            props: {
                value: {
                    type: Array,
                    default: () => []
                },
                remoteMethod: Function,
                updateCustomer: Function,
                placeholder: String
            },
            methods: {
                input(value) {
                this.$emit('input', value)
                }
            },
            render(h) {
                return (
                <base-select
                    value={this.value}
                    placeholder={this.placeholder}
                    remoteMethod={this.remoteMethod}
                    onInput={this.updateCustomer}
                />
                )
            }
        }
  },
  mixins: [AuthMixin],
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      searchParams: {
        memberName: '',
        pageSize: 10,
        pageNum: 1
      },
      currentEventType: {},
      multipleSelection: [],
      Page: new Page(),
      visible: false,
      columns: [],
      columnNum: 1,
      exportColumnList: [],
      AllConsultTypeList:[],
      navWidth: window.innerWidth - 120,
      loading: true,
      advancedColumnNumStorageKey: StorageKeyEnum.DoorUserListAdvancedColumnNum,
      searchParamsAll: {},
      doorLoginListExport,
      stateRes: {
      },
      auth: {},
      tagList: [],
      customerFields:[],
      tableContainerHeight:'440px',
      saveDialogVisible: false,
        saveForm: {
            memberId: null,
            name: '', // 新建联系人方式的联系人
            phone: '',
            type:0,
            linkman:'', // 更新原有联系人方式的联系人
            email:'', // 邮箱
        },
        saveFormRules: {
            name: [{ required: true, message: i18n.t('im.chatMixin.tips1'), trigger: ['blur', 'change']}],
            phone: [
            { required: true, message: i18n.t('im.chatMixin.tips2'), trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                if (TEL_REG.test(value) || PHONE_REG.test(value)) {
                    callback();
                } else {
                    callback(new Error(i18n.t('im.chatMixin.tips3')));
                }
                },
            },
            ],
            email: [
            { required: true, message: i18n.t('im.chatMixin.tips4'), trigger: 'blur' },
            ],
            customer:[
            { 
                required:true,
                validator:(rule, value, callback)=>{
                if(this.customer[0].value){
                    callback();
                }else{
                    callback(new Error(i18n.t('im.chatMixin.tips5')));
                }
                }, 
                trigger: 'blur'
            },
            ],
            type: [
            { required: true, message: i18n.t('im.chatMixin.tips6'), trigger: ['blur', 'change']},
            ],
            linkman: [{ required: true, message: i18n.t('im.chatMixin.tips7'), trigger: ['blur', 'change']}],
        },
        customer: [
            {
                value: '',
                label: ''
            }
        ],
        customerField: {
            isSystem: 1,
            fieldName: 'customer',
            displayName: i18n.t('common.base.customer'),
            formType: 'customer',
            defaultValue: null,
            isNull: 0,
            isSearch: 0,
            placeHolder: ''
        },
    };
  },
  computed: {
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this,{
            tagList: this.tagList
        })
      ];
    },
    // 当前选中的ids
    selectedIds() {
      return this.multipleSelection.map(p => p.id);
    },

    /** 列表字段 */
    listFields() {
      const columnFields = [...this.customerFields, ...getColumnFields(this)];

      return []
        .concat(columnFields)
        .filter(f => f.formType !== 'separator' && f.formType !== 'info')
        .sort((a, b) => a.orderId - b.orderId);
    },
    exportIn() {
      return AuthUtil.hasAuth(this.auth, 'CASE_CONVERSATION_EXPORT')
    },
    allowImView() {
      return this.globalIsHaveImViewDetailAuth
    }
  },

  async mounted() {
    // 获取缓存的pagesize
    const localStorageData = await this.getLocalStorageData();
    this.searchParams.pageSize = localStorageData[DOOR_USER_PAGE_SIZE_KEY] || 10;
    this.initialize(); // 获取初始化数据
    this.search();
    this.getTag();
    this.getAuthByRootInitData();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
        that_.navWidth = window.innerWidth - 120;
      }, 500)
    })
  },
  methods: {
    getTag() {
        getUserTag().then(result => {
            if (!result.success) {
                return Message.error(result.message);
            }
            let tagList = Object.keys(result.data)
            this.tagList = tagList.map((item) => {
                return {
                    text: result.data[item],
                    value: item
                }
            })
        })
        .catch(error => {
            console.warn(error);
            Message.error(this.$t('common.base.tip.systemIsError'));
        });
    },
    // 获取window._init auth
    getAuthByRootInitData() {
      const rootWindow = getRootWindow(window)
      const _initData = JSON.parse(rootWindow?._init || '{}')
      this.auth = _initData?.user?.auth || {}
    },
    // 获取列表
    queryConversationList(params = {}) {
      this.loading = true;
      loginRecordPage(params)
        .then(res => {
          if (res.code == '200') {  
            this.Page = res.data || {};
          }else{
            this.$message.error(res?.message ?? this.$t('common.base.tip.systemIsError'))
          }
        })
        .catch(err => {
          console.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 搜索
    search() {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel
        ? this.$refs.searchPanel.buildParams()
        : {};
      // 处理数据
      const { loginTimeStart, tag, customerId = '' } = advancedSearchParams
      if (loginTimeStart) {
        advancedSearchParams.timeStartL = loginTimeStart.getTime()
        advancedSearchParams.timeEndL = loginTimeEnd.getTime()
      }
      
      const searchParams = {
        ...this.searchParams,
        ...advancedSearchParams,
        customerId,
      };
      this.searchParamsAll = searchParams;
      this.visible = false;

      this.queryConversationList(searchParams);
    },

    // 重置
    resetParams() {
      this.$emit('reset')
    },

    // 高级搜索
    panelSearchAdvancedToggle() {
      this.visible = true;
    },

    /**
     * @description: 导出（全部）
     * @param {Boolean} isExportAll 是否导出全部
     */
    async handleExport(isExportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}列表数据.xlsx`;
      if (!isExportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel;
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty');
      }

      const LocalStorageData = await this.getLocalStorageData();
      let exportCheckedData = LocalStorageData.exportCheckedData;

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true,
        };
      }

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData);
    },

    async initialize(isEventStatus) {
      // Todo接口调用更改
      // 清除导出配置的缓存
      localStorage.removeItem('checkedMap');
      localStorage.removeItem('checkedGroupArr');
      localStorage.removeItem('isCheckedAll');
      this.columns = this.listFields;
      this.buildColumns(); // 构建表格/选择列字段
      this.buildExportColumns(); // 构建导出字段
    },

    // 构建列表项
    async buildColumns() {
      // 获取缓存在本地的选择列配置
      const localStorageData = await this.getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let listFields = this.listFields; // 本地默认的表格项字段
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        listFields = this.buildSortFields(listFields, localColumns);
      }

      const columns = listFields.map(col => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let { width } = col;
        let localField = localColumns[col.field]?.field || null;
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : localField.width;
          }
          show = localField.show !== false;
        } else {
          show = true;
        }

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
      });
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },

    // 构建导出项
    buildExportColumns() {
      // im列表信息
      // 系统信息
      const systemInfo = {
        label: this.$t('common.form.fieldGroupName.system'),
        value: 'systemChecked',
        columns: [...getExportSystemInfo()].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };
      // 自定义字段
      const attrInfo = {
        label: this.$t('common.form.fieldGroupName.attribute'),
        value: 'attrChecked',
        columns: [...this.customerFields].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };
      this.exportColumnList = [systemInfo,attrInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });
    },

    // 打开选择列
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, this.currentEventType);
    },

    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || [];
      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return row.id;
    },

    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    // 表格选择操作
    handleSelection(selection) {
      this.multipleSelection = selection;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    // 排序变化
    sortChange(option) {
      const { column, order, prop } = option;
      const sortedField = this.columns.filter(item => item.fieldName === prop)[0] || {};
      if (column === null) {
        this.searchParams.orderDetail = {};
      } else {
        this.searchParams.orderDetail = {
          column: sortedField.sortName,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          type: sortedField.dataType,
          isSystem: sortedField.isSystem,
        };
      }
      this.search();
    },

    // 页码跳转
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.Page.list = [];
      this.search();
    },

    // 页大小改变
    handleSizeChange(pageSize) {
      this.saveDataToStorage(DOOR_USER_PAGE_SIZE_KEY, pageSize);
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;
      this.search();
    },

    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    // 构建导出参数
    buildExportParams(checkedMap, ids) {
      const { systemChecked = [],attrChecked = [] } = checkedMap;

      let exportAll = !ids || !ids.length;
      let exportTotal = exportAll ? this.Page.total : this.selectedIds.length;
      const exportSearchModel = {
        exportTotal,
        ...this.searchParamsAll,
      };

      let params = {
        dataTotal: exportTotal,
        exportSearchModel: JSON.stringify(exportSearchModel),
      };
      let export_sys = this.exportData([...systemChecked,...attrChecked]);
      if (export_sys.indexOf('loginAddress')) {
        export_sys.push('loginProvince')
      }
      params['ids'] = exportAll ? '' : this.selectedIds.join(',');
      params['checked'] = export_sys
        .map(item => {
          return item;
        })
        .join(',');

      return params;
    },

    /**
     * 导出数据
     */
    exportData(list = []) {
      const export_list = this.exportColumnList;
      let xlistColumns = [];
      export_list.forEach((xlist) => {
        xlistColumns = xlistColumns.concat(xlist.columns);
      });

      return xlistColumns
        .map(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item;
            }
            return v.fieldName === item;
          });
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName;
          }
        })
        .filter(item => {
          return item;
        });
    },

    // 导出提示
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },

    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.Page.total > max
        ? this.$t('common.base.tip.exportMostTip')
        : null;
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(DOOR_USER_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(DOOR_USER_LIST_KEY, JSON.stringify(data));
    },
    updateRes(data, checkData){
      if(checkData && checkData.parent) {
        this.$track.clickStat(this.$track.formatParams('QUICK_SEARCH', checkData.parent.label));
      }
      this.stateRes = data
      let solveStatus = data.jjzt[0]
      let conversationStatus = data.hhzt[0]
      if(solveStatus == 'all'){
        solveStatus = ''
      }
      if(conversationStatus == 'all'){
        conversationStatus = ''
      }
      this.searchParams.solveStatus = solveStatus
      this.searchParams.conversationStatus = conversationStatus
      this.search()
    },
    /** 列表拨打电话 */
    async makePhoneCall(phone, isLinkman) {
      if(!this.customerSetting.linkmanOn && isLinkman) return;
      try {
        ctiCallOut(phone) // taskType:'customer'
      } catch (error) {
        console.error(error);
      }
    },
    // 存为客户
    createCustomer(memberId, linkmanPhone, lmEmail) {
        memberId = memberId || ''
        linkmanPhone = linkmanPhone || ''
        lmEmail = lmEmail || ''
        let fromId = window.frameElement.getAttribute('id');
        const param = {
            type: PageRoutesTypeEnum.PageCreateCustomer,
            reload: true,
            params: `lmPhone=${linkmanPhone}&bizTypeId=${memberId}&lmEmail=${lmEmail}&bizTypeModule=DOOR_DATA_DASHBOARD`,
            fromId
        }
        openAccurateTab(param)
    },
    openCustomer(id) {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    saveLinkman(linkmanPhone, linkmanEmail, memberId) {
        this.saveDialogVisible = true
        this.saveForm.phone = linkmanPhone
        this.saveForm.email = linkmanEmail
        this.saveForm.memberId = memberId
    },
    saveDialogClosed() {
        this.$refs.saveFormRef.resetFields()
    },
    async saveUserClick(){
        await this.saveUser(this.imId)
        // this.GetInitData()
    },
    saveUser(conversationId) {
        return new Promise((resolve, reject)=>{
            this.$refs.saveFormRef.validate(async valid => {
                if (!valid) return reject(this.$t('im.chatMixin.tips8'))
                const params = {}
                const {email, linkman, name, phone, type, memberId } = this.saveForm
                params.conversationId = conversationId
                params.customerId = this.customer[0].value
                params.customerName = this.customer[0].label
                params.phoneNumber = phone
                params.email = email
                params.memberId = memberId
                if(type == 0){
                    params.linkmanName = name
                }else{
                    params.linkmanName = linkman[0].name
                    params.linkmanId = linkman[0].id
                }
                if (this.isWeChat && !params.phoneNumber) {
                    this.loading = false
                    return this.$platform.alert(this.$t('im.chatMixin.tips9'))
                }
                let confirmTitle = type == 0 ? this.$t('im.chatMixin.tips10') : this.$t('im.chatMixin.tips11')
                let confirmText = type == 0 ? this.$t('im.chatMixin.tips12') : this.$t('im.chatMixin.tips13')
                const confirmRes = await this.$confirm(confirmText, confirmTitle).then(() => {
                    return Promise.resolve(true)
                }).catch(() => {
                    this.loading = false
                    return Promise.resolve(false)
                });
                if(!confirmRes) return
                try {
                    const { code, message } = await unknownUserRelationLinkman(params)
                    if (code !== '200'){
                        this.$platform.notification({
                            title: this.$t('common.base.tip.saveFail'),
                            message: message || '',
                            type: 'error'
                        })
                        return reject(message)
                    }
                    this.$refs.saveFormRef.resetFields()
                    this.saveDialogVisible = false
                    this.isInformation = false
                    this.$platform.notification({
                        title: this.$t('common.base.tip.saveSuccess'),
                        type: 'success'
                    })
                    // 页面刷新
                    this.$emit('refresh')
                    resolve()
                } catch (e) {
                    console.error(e)
                    reject(this.$t('common.base.tip.systemIsError'))
                } finally {
                    this.loading = false
                }
            })
        })
    },
    searchCustomer(params) {
        const pms = params || {}
        return this.$http.post('/customer/list', pms)
            .then(res => {
            if (!res || !res.list) return
            if (res.list) {
                res.list = res.list.map(customer =>
                    Object.freeze({
                        label: customer.name,
                        value: customer.id
                    })
                )
            }
            return res
        })
        .catch(e => console.error(e))
    },
    updateCustomer(value) {
        this.customer = value
        this.$refs.saveFormRef.validateField('customer');
    },
    // 搜索linkman联系人
    async searchLinkman(params = {}) {
        let customerId = this.customer[0]?.value
        if(!customerId) return this.$message.error(this.$t('im.chatMixin.tips14'))
        params = {...params, customerId}
        try {
            let { result } = await TaskApi.getTaskCustomerLinkman(params);
            if (!result || !result.list) return;
            result.list = result.list.map((linkman) =>
                linkmanSelectConversion(linkman)
            );
            return result;
        } catch (error) {
            console.warn('task-edit-form: searchProduct -> error', error);
        }
    },
    advancedSearch(){
      this.searchParams.pageNum = 1
      this.search()
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 8 - 32;
        // console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        // console.log(pxArray, 'pxArray')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__body .el-table__row td .cell,
.el-table__header thead tr th .cell {
  min-height: 40px;
  height: auto;
}
.OpenLink {
  color: $color-primary-light-6;
  cursor: pointer;
  height: 20px;
  margin-bottom: 5px;
  &:last-child{
    margin-bottom: 0;
  }
}
.OpenLink:hover {
  text-decoration: underline;
}
.event-list {
  .search-input {
    width: 440px;
  }

  > div {
    border-radius: 4px;
  }

  .filter-wrapper {
    .searh-input-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      // border-bottom: 1px solid #f2f2f2;
      .advanced-search-btn {
        @include fontColor;
      }
      .base-search-group {
        margin-right: 24px;
      }
    }
    .filter-tab {
      &__item {
        display: flex;
        flex-wrap: wrap;
        line-height: 32px;
        border-bottom: 1px solid #f2f2f2;
        &:last-child {
          border-bottom: 0;
        }
      }
      &__label {
        background: #f5f5f5;
        width: 108px;
        text-align: center;
        color: #666;
      }
      &__content {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        height: auto;
        .content-item {
          display: inline-block;
          width: 130px;
          overflow: hidden;
          padding-left: 10px;
          cursor: pointer;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: grey;
          &:hover {
            color: #333;
          }
          .content-item-label.actived {
            color: $color-primary-light-6 !important;
          }
        }
        .fold-btn {
          position: absolute;
          right: 10px;
        }
      }
      &__content.fold {
        height: 30px;
        overflow: hidden;
      }
    }
    .filter-box{
      padding: 0 16px 16px;
    }
  }

  .common-list-view__v2 {
    padding-top:0;
    padding-bottom:0;
    .operate-box {
      .cur-point {
        color: #595959;
      }
      display: flex;
      justify-content: space-between;
      align-items: center;
      > div {
        display: flex;
        align-items: center;
        .icon-dingyuetongzhiguanli {
          font-size: 14px;
          &.actived {
            color: $color-primary-light-6;
          }
        }
      }
    }
  }
}
.reset-btn {
  background: #f5f8fa;
}
.tag_div{
    display: flex;
    .el-tag{
        margin-right: 10px;
    }
}
</style>
